
require("dotenv").config();
const Koa = require("koa");
const Router = require("koa-router");
const cors = require("@koa/cors");
const fs = require("fs");
const path = require("path");
const serve = require("koa-static");
// const crypto = require("crypto");
const handleMenu = require("./handleMenu.js");
const Jsons = require("./jsonClass.js");
const jsonClass = new Jsons();
// const { searchData } = require("./search.js");
const { questionList, handleQuestion } = require("./question.js");
// 创建Koa应用实例
const app = new Koa();
const router = new Router();

// 静态文件服务
app.use(serve(path.join(__dirname, "public")));

// ================== API路由定义 ==================
// 登录接口
router.post("/api/login-module/login", jsonClass.login);
// 登出接口
router.post("/api/login-module/logout", jsonClass.logout);
// 获取JSON文件数据（支持分页）
router.get("/api/binary/:path", jsonClass.validateToken.bind(jsonClass), jsonClass.validatePath.bind(jsonClass), jsonClass.getJson.bind(jsonClass));
// 获取字典数据
router.get("/api/binary/dict/:dict", jsonClass.validateToken.bind(jsonClass), jsonClass.validatePath.bind(jsonClass), jsonClass.getDict.bind(jsonClass));
// 获取题库数据(支持分页)
router.get("/api/binary/question/:path", jsonClass.validateToken.bind(jsonClass), jsonClass.validatePath.bind(jsonClass), questionList.bind(jsonClass));
// 操作接口
router.post("/api/binary/handle/:operation", jsonClass.validateToken.bind(jsonClass), jsonClass.handleBinary.bind(jsonClass));
// 菜单操作接口
router.post("/api/binary/menu/:operation", jsonClass.validateToken.bind(jsonClass), handleMenu.bind(jsonClass));
// 创建JSON文件（无需token验证）
router.post("/api/binary/create-file", jsonClass.createJsonFile.bind(jsonClass));
// 获取models目录下的3D模型文件（无需token验证）
router.get(/^\/api\/models\/([^/]+)\/(.+)$/, jsonClass.getModel.bind(jsonClass));
// 应用中间件
app.use(
  cors({
    origin: (ctx) => {
      // 更灵活的安全控制，允许本地开发源
      const allowedOrigins = ["http://192.168.110.165", "http://127.0.0.1:5500"];
      const origin = ctx.headers.origin;
      if (allowedOrigins.includes(origin)) {
        return origin;
      }
      return "";
    },
    credentials: true,
    allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allowHeaders: ["Content-Type", "Authorization"],
  })
);

// 解析请求体
app.use(require("koa-bodyparser")());

app.use(router.routes());
app.use(router.allowedMethods());

// 错误处理
app.on("error", (err, ctx) => {
  console.error("服务器错误:", err);
  ctx.body = {
    success: false,
    code: 500,
    message: "内部服务器错误",
  };
});

// 启动服务器
const PORT = process.env.JSON_PORT || 4000;
app.listen(PORT, () => {
  console.log(`
  ███████╗██╗██╗     ███████╗    ███████╗███████╗██████╗ ██╗   ██╗███████╗██████╗ 
  ██╔════╝██║██║     ██╔════╝    ██╔════╝██╔════╝██╔══██╗██║   ██║██╔════╝██╔══██╗
  █████╗  ██║██║     █████╗      ███████╗█████╗  ██████╔╝██║   ██║█████╗  ██████╔╝
  ██╔══╝  ██║██║     ██╔══╝      ╚════██║██╔══╝  ██╔══██╗╚██╗ ██╔╝██╔══╝  ██╔══██╗
  ██║     ██║███████╗███████╗    ███████║███████╗██║  ██║ ╚████╔╝ ███████╗██║  ██║
  ╚═╝     ╚═╝╚══════╝╚══════╝    ╚══════╝╚══════╝╚═╝  ╚═╝  ╚═══╝  ╚══════╝╚═╝  ╚═╝
  
  文件服务已启动:
  - 本地地址: http://localhost:${PORT}
  - 可访问GLBS目录内容
  - 安全限制: 仅允许来自指定源的请求
  
  警告: 此服务仅限本地开发使用!
  `);
});
